package com.example.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import com.example.entity.User;
import com.example.service.UserService;
import com.example.service.UserSessionService;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

public class AuthTokenFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private UserSessionService userSessionService;
    
    @Autowired
    private UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        logger.debug(">>> Entering AuthTokenFilter for request: {}", request.getRequestURI());
        try {
            String jwt = parseJwt(request);
            logger.debug(">>> Parsed JWT: {}", jwt);

            if (jwt != null) {
                boolean isValidJwt = jwtUtils.validateJwtToken(jwt);
                logger.debug(">>> JWT validation result: {}", isValidJwt);

                if (isValidJwt) {
                    boolean isSessionValid = userSessionService.validateSession(jwt);
                    logger.debug(">>> Custom session validation result: {}", isSessionValid);

                    if (isSessionValid) {
                        String username = jwtUtils.getUserNameFromJwtToken(jwt);
                        logger.debug(">>> Username from JWT: {}", username);

                        userSessionService.updateLastAccessTime(jwt);

                        // 获取用户信息
                        User user = userService.getUserByUsername(username);
                        if (user != null) {
                            // 从JWT中获取角色信息而不是重新查询数据库
                            List<String> rolesFromJwt = jwtUtils.getRolesFromJwtToken(jwt);
                            logger.debug(">>> Roles from JWT: {}", rolesFromJwt);
                            
                            List<GrantedAuthority> authorities = rolesFromJwt.stream()
                                    .map(SimpleGrantedAuthority::new)
                                    .collect(Collectors.toList());
                            
                            // 构建UserDetails对象，使用JWT中的角色
                            UserDetailsImpl userDetails = UserDetailsImpl.build(user, rolesFromJwt);
                            
                            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                    userDetails, null, authorities);
                            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                            SecurityContextHolder.getContext().setAuthentication(authentication);
                            Authentication authResult = SecurityContextHolder.getContext().getAuthentication();
                            logger.debug(">>> SecurityContextHolder updated. Is authentication present? {}, Authorities: {}", 
                                    authResult != null && authResult.isAuthenticated(), 
                                    authResult != null ? authResult.getAuthorities() : "none");
                        } else {
                            logger.warn(">>> User not found: {}", username);
                        }
                    } else {
                        logger.warn(">>> Custom session is NOT valid for token: {}", jwt);
                    }
                }
            } else {
                logger.debug(">>> JWT token is null or invalid, proceeding without authentication.");
            }
        } catch (Exception e) {
            logger.error(">>> Error setting user authentication: {}", e.getMessage(), e);
        }

        filterChain.doFilter(request, response);
        logger.debug("<<< Exiting AuthTokenFilter for request: {}", request.getRequestURI());
    }

    private String parseJwt(HttpServletRequest request) {
        String headerAuth = request.getHeader("Authorization");
        logger.trace(">>> Raw Authorization Header: {}", headerAuth);
        if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) {
            return headerAuth.substring(7);
        }
        return null;
    }
}